package com.tools.cleanmaster.manager;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.widget.RemoteViews;

import com.tools.cleanmaster.CleanApplication;
import com.tools.cleanmaster.R;
import com.tools.cleanmaster.store.GlobalConfigSharedPrefManager;
import com.tools.cleanmaster.ui.card.newresult.NewResPageUtils;
import com.tools.cleanmaster.utils.FeatureConfig;
import com.tools.cleanmaster.utils.LogHelper;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * 推荐应用更新管理
 * CreatedXXX on 2017/9/4.
 */

public class RecommendUpdateManager {

    private Context mContext;
    private static RecommendUpdateManager mInstance;
    private int limitVersionCode = Integer.MIN_VALUE;
    private boolean totalSwitch = false;
    private boolean splashSceneSwitch = false;
    private boolean notificationSceneSwitch = false;
    private int currentVersionCode;
    private static final String TAG = "UpdateManager";
    private static final String UPDATE_GUIDE_ACTION = CleanApplication.getInstance().getPackageName() + "update.guide.action";
    private NotificationManager mNm;
    private static final int UPDATE_GUIDE_NOTIFICATION = 1033;

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(final Context context, Intent intent) {
            String action = intent.getAction();
            if (TextUtils.equals(action, UPDATE_GUIDE_ACTION)) {
                afterNotificationClick(context);
            }
        }
    };

    private RecommendUpdateManager(Context context) {
        this.mContext = context;
        currentVersionCode = GlobalStateMgr.getInstance().getVersionCode(mContext, -1);
        mNm = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
        IntentFilter filter = new IntentFilter();
        filter.addAction(UPDATE_GUIDE_ACTION);
        try {
            mContext.registerReceiver(receiver, filter);
        } catch (Throwable e) {
            if (FeatureConfig.DEBUG_LOG) {
                LogHelper.i("TAG", "register config receiver error!");
            }
        }
    }

    public static RecommendUpdateManager getInstance(Context context) {
        if (mInstance == null) {
            synchronized (RecommendUpdateManager.class) {
                if (mInstance == null) {
                    mInstance = new RecommendUpdateManager(context);
                }
            }
        }
        return mInstance;
    }

    public void parseCloudConfig(String body) {
        if (body.isEmpty()) {
            return;
        }
        try {
            JSONObject jsonObject = new JSONObject(body);
            limitVersionCode = jsonObject.optInt("version_code", Integer.MIN_VALUE);
            splashSceneSwitch = jsonObject.optBoolean("splash_switch", false);
            notificationSceneSwitch = jsonObject.optBoolean("notification_switch", false);
            totalSwitch = jsonObject.optBoolean("total_switch", false);
            if (shouldShowNotificationUpdate()) {
                LogHelper.d(TAG, "开始触发通知栏场景");
            }
        } catch (JSONException e) {
            if (FeatureConfig.DEBUG_LOG) {
                throw new RuntimeException(e);
            }
        }
    }

    public boolean shouldShowSplashUpdate() {
        if (!totalSwitch) {
            LogHelper.d(TAG, "总开关为关，不展示");
            return false;
        }
        if (!splashSceneSwitch) {
            LogHelper.d(TAG, "闪屏推荐更新开关为关，不展示");
            return false;
        }
        if (currentVersionCode > limitVersionCode) {
            LogHelper.d(TAG, "当前版本号为:" + currentVersionCode + "大于云端下发版本号:" + limitVersionCode + "，不展示");
            return false;
        }
        LogHelper.d(TAG, "当前的versionCode为 " + currentVersionCode);
        return (System.currentTimeMillis()
                - GlobalConfigSharedPrefManager.lastShowUpdateSceneTime(GlobalConfigSharedPrefManager.UPDATE_TYPE_SPLASH)
                > 24 * DateUtils.HOUR_IN_MILLIS);
    }

    public boolean shouldShowNotificationUpdate() {
        if (!totalSwitch) {
            LogHelper.d(TAG, "总开关为关，不展示");
            return false;
        }
        if (!notificationSceneSwitch) {
            LogHelper.d(TAG, "通知推荐更新开关为关，不展示");
            return false;
        }
        if (currentVersionCode > limitVersionCode) {
            LogHelper.d(TAG, "当前版本号为:" + currentVersionCode + "大于云端下发版本号:" + limitVersionCode + "，不展示");
            return false;
        }
        LogHelper.d(TAG, "当前的versionCode为 " + currentVersionCode);
        int interval = GlobalConfigSharedPrefManager.firstShowUpdateNotification() ? 12 : 24;
        return (System.currentTimeMillis()
                - GlobalConfigSharedPrefManager.lastShowUpdateSceneTime(GlobalConfigSharedPrefManager.UPDATE_TYPE_NOTIFICATION)
                > interval * DateUtils.HOUR_IN_MILLIS);
    }

    public void showSceneNotification() {
        if (!shouldShowNotificationUpdate()) {
            return;
        }
        RemoteViews contentViews = new RemoteViews(mContext.getPackageName(),
                R.layout.update_guide_notification_layout);
        Intent intent = new Intent(UPDATE_GUIDE_ACTION);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent,
                PendingIntent.FLAG_CANCEL_CURRENT);
        Notification notification = new Notification();
        notification.icon = R.mipmap.ic_launcher;
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notification.contentView = contentViews;
        notification.contentIntent = pendingIntent;
        mNm.notify(UPDATE_GUIDE_NOTIFICATION, notification);
        updatePageReport("update_no", "show");
        GlobalConfigSharedPrefManager.setlastShowUpdateSceneTime(GlobalConfigSharedPrefManager.UPDATE_TYPE_NOTIFICATION,
                System.currentTimeMillis());
        GlobalConfigSharedPrefManager.setFirstShowUpdateNotification(false);
        // 通知栏上报5级活跃
    }

    public void afterNotificationClick(Context context) {
        if (mNm != null) {
            mNm.cancel(UPDATE_GUIDE_NOTIFICATION);
        }
        String medium = NewResPageUtils.GOOGLE_PLAY_SOURCE_MEDIUM_NEW_RESULTCARD;
        //todo 安装应用
        updatePageReport("update_no", "clc");
        context.unregisterReceiver(receiver);
    }

    public static void updatePageReport(String scene, String action) {

    }
}
